import React from 'react';
import util from 'util';
import {
    Collapse,
    Row,
    Col,
    Form,
    Input,
    Button,
    Checkbox,
    Radio,
    Tooltip,
    Icon,
    Table,
    Alert,
    Modal,
    message
} from 'antd';
import {Search, DictForm, ChildrenForm} from './components/form';
import {hashHistory} from 'react-router';

const FormItem = Form.Item;
const confirm = Modal.confirm;
var Panel = Collapse.Panel;

@Form.create()
class Dict extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            childrenData: [],
            visible: false,
            dictModalTitle: "新增数据字典信息",
            loading: false,
            childrenFormData: {},
            diceFormData: {},
            dictTableLoading: false,
            childrenTableLoading: false,
            queryChildrenParams: null,
            key1: Math.random(),
            key2: Math.random(),
            CBState: true,
            bloading: false,
            optionData: []
        };
        this.params = {};
        this.willUnmount = true;
        this.dic;
    }

    componentWillUnmount() {
        this.willUnmount = false;
    }

    showLoading(type) {
        if (type === "dict") {
            this.setState({
                dictTableLoading: true
            });
        } else if (type === "children") {
            this.setState({
                childrenTableLoading: true
            });
        }
        setTimeout(function () {
            if (this.willUnmount) {
                this.setState({
                    dictTableLoading: false,
                    childrenTableLoading: false
                });
            }
        }.bind(this), 10000);
    }

    search(params) {
        params.groupdict = '';
        if ((params.dict == "" || params.dict == undefined) && params.dictname == "" || params.dictname == undefined) {
            params.groupdict = 'ROOT';
        }
        console.log("log/index.js 接受到的参5：", params);
        this.queryDict(params);
        this.setState({
            CBState: true,
            childrenData: []
        })
    }

    componentDidMount() {
        var oprates = util.getLocalObj("roleids");
        console.log(oprates);
        if (oprates[0] == "SYSTEM") {
            this.setState({
                add: true,
                edit: true,
                delete: true
            });
        } else {
            for (var i = 0; i < oprates.length; i++) {
                switch (oprates[i]) {
                    case "441":
                        this.setState({
                            add: true
                        });
                        break;
                    case "442":
                        this.setState({
                            edit: true
                        });
                        break;
                    case "443":
                        this.setState({
                            delete: true
                        });
                        break;
                }
            }
        }

        this.showLoading("dict");
        util.httpRequest({
            type: "POST", url: 'dict010301.json', params: {'groupdict': 'ROOT'}, success: function (result) {
                if (result.ret_code === "0000") {
                    let optionDatas = [];
                    for (let {dict, dictname} of result.rows) {
                        optionDatas.push({"itemkey": dict, "itemval": dictname});
                    }

                    this.setState({
                        dataSource: result.rows,
                        total: result.total,
                        optionData: optionDatas
                    });
                }
            }.bind(this), complete: function () {
                if (this.willUnmount) {
                    this.setState({
                        dictTableLoading: false
                    })
                }
            }.bind(this)
        });
    }

    queryDict(params) {
        //params = util.extend({page: "1", rows: "10"}, params
        this.showLoading("dict");
        params.groupdict = "ROOT";
        util.httpRequest({
            type: "POST", url: 'dict010301.json', params: params || {}, success: function (result) {
                if (result.ret_code === "0000") {

                    this.setState({
                        dataSource: result.rows,
                        total: result.total
                    });
                }
            }.bind(this), complete: function () {
                if (this.willUnmount) {
                    this.setState({
                        dictTableLoading: false
                    })
                }
            }.bind(this)
        });
    }

    queryChildren(params) {

        this.setState({
            childrenTableLoading: true
        });

        util.httpRequest({
            type: "POST", url: 'dict010306.json', params: params || {}, success: function (result) {
                if (result.ret_code === "0000") {
                    this.params.dict = params.dict;
                    this.setState({
                        childrenData: result.rows,
                        CBState: false
                    })
                }
            }.bind(this),
            complete: function () {
                if (this.willUnmount) {
                    this.setState({
                        childrenTableLoading: false
                    })
                }
            }.bind(this)
        });
    }

    showDictModal(modalTitle) {
        this.setState({
            dictVisible: true,
            dictModalTitle: modalTitle,
            key1: Math.random()
        })
    }

    showChildrenModal(modalTitle) {
        this.setState({
            childrenVisible: true,
            dictModalTitle: modalTitle,
            key2: Math.random()
        })
    }

    handleSubmit(type, operate, e) {
        e.preventDefault();
        this.setState({
            bloading: true
        });
        this.refs.form.validateFields((errors, values) => {
            if (!!errors) {
                return;
            }
            let that = this;
            let closeBloading = function () {
                that.setState({
                    bloading: false
                });
            };
            if (type === "dict") {
                if (operate === "modify") {
                    values.dict_id = this.params.dictkey;
                    util.httpRequest({
                        type: "POST", url: 'dict010303.json', params: values || {}, success: function (result) {
                            if (result.ret_code === "0000") {
                                this.hideModal();
                                this.queryDict({'groupdict': 'ROOT'});
                                this.updateLocalDict();
                            } else {
                                //@TODO 添加失败方法处理1
                            }
                        }.bind(this),
                        complete: function () {
                            closeBloading();
                        }
                    });
                } else if (operate === "add") {
                    let {groupdict}=values;
                    if (groupdict == "10000") {
                        values.trans_channel_id = "1";
                    } else if (groupdict == "app") {
                        values.trans_channel_id = "2";
                    }
                    values.groupdict = "ROOT"
                    util.httpRequest({
                        type: "POST", url: 'dict010302.json', params: values || {}, success: function (result) {
                            if (result.ret_code === "0000") {
                                this.hideModal();
                                this.queryDict({'groupdict': 'ROOT'});
                                this.updateLocalDict();
                            } else {
                                //@TODO 添加失败方法处理
                            }
                        }.bind(this),
                        complete: function () {
                            closeBloading();
                        }
                    });
                }
            } else if (type === "children") {
                if (operate === "modify") {
                    values.olditemkey = this.params.olditemkey;
                    values.dict_item_id = this.params.childkey;
                    util.httpRequest({
                        type: "POST", url: 'dict010308.json', params: values || {}, success: function (result) {
                            if (result.ret_code === "0000") {
                                this.hideModal();
                                this.updateLocalDict();
                                this.queryChildren({dict: this.params.dict});
                            } else {
                                //@TODO 添加失败方法处fsd2
                            }
                        }.bind(this),
                        complete: function () {
                            closeBloading();
                        }
                    })
                } else if (operate === "add") {
                    values.trans_channel_id = this.params.trans_channel_id;
                    util.httpRequest({
                        type: "POST", url: 'dict010307.json', params: values || {}, success: function (result) {
                            if (result.ret_code === "0000") {
                                this.hideModal();
                                this.updateLocalDict();
                                this.queryChildren({dict: this.params.dict});
                            } else {
                                //@TODO 添加失败方法处理
                            }
                        }.bind(this),
                        complete: function () {
                            closeBloading();
                        }
                    })
                }
            }
        });
    }

    handleCancel() {
        this.hideModal();
    }

    hideModal() {
        this.setState({
            childrenVisible: false,
            dictVisible: false,
            bloading: false
        })
    }

    onRowClick(record, index) {
        //if(record.isleaf=="true"){
        if (!record.children) {
            console.log(record);
            this.params.trans_channel_id = record.channel_id;
            this.queryChildren({dict: record.dict});
            this.dic = record.dict
        }
        //}else{
        //    this.showLoading("dict324");
        //    util.httpRequest({
        //        type: "POST", url: 'dict010301.json', params:{'groupdict':record.dict,'groupdict':'ROOT'}, success: function (result) {
        //            if (result.ret_code === "0000") {
        //                let list=this.state.dataSource;
        //                //for(let i=0;i<result.rows.length;i++){
        //                //    result.rows[i].isleaf="1";
        //                //}1
        //                list[index].children=result.rows;
        //
        //                console.log("tablelist:",list);
        //                this.setState({
        //                    dataSource: list,
        //                    total: result.total
        //                });
        //            }
        //        }.bind(this), complete: function () {
        //            if (this.willUnmount) {
        //                this.setState({
        //                    dictTableLoading: false
        //                })
        //            }
        //        }.bind(this)
        //    });
        //}
    }

    addDict() {
        this.setState({
            isAdd: true,
            diceFormData: {},
            operate: "add"
        });
        this.showDictModal("新增数据字典信息");
    }

    addChildren() {
        this.setState({
            isAdd: true,
            operate: "add",
            childrenFormData: {
                dict: this.params.dict
            }
        });
        this.showChildrenModal("新增子项数据字典信息");
    }

    onTongBu() {
        util.httpRequest({
            type: "POST", url: 'dict010310.json', params: {"dict": this.dic}, success: function (result) {
                if (result.ret_code === "0000") message.success('同步成功！')

            }.bind(this)
        });
    }

    updateLocalDict() {
        util.httpRequest({
            type: "POST", url: 'dict010305.json', params: {"dict": ""}, success: function (result) {
                console.log("getdic", result);
                if (result.rows) {
                    localStorage.setItem("sys_dic", JSON.stringify(result.rows));
                }
            }.bind(this)
        });
    }

    modify(type, record, e) {
        if (type === "dict") {
            console.log(record);
            this.params.dictkey = record.key;
            this.setState({
                isAdd: false,
                diceFormData: record,
                operate: "modify"
            });
            this.showDictModal("修改数据字典信息");
        } else if (type === "children") {
            console.log(record);
            this.params.olditemkey = record.itemkey;
            this.params.childkey = record.key;
            this.setState({
                isAdd: false,
                childrenFormData: record,
                operate: "modify"
            });
            this.showChildrenModal("修改子项数据字典信息");
        }
        e.stopPropagation();
    }

    remove(type, record) {
        let that = this;
        confirm({
            title: '是否删除？',
            onOk() {
                if (type == "dict") {
                    that.setState({
                        dictTableLoading: true
                    });
                    record.dict_id = record.key;
                    util.httpRequest({
                        type: "POST", url: "dict010304.json", params: record, success: function (res) {
                            if (res.ret_code === "0000") {
                                that.queryDict({'groupdict': 'ROOT'});
                                that.updateLocalDict();
                            } else {
                                //@TODO 字典数据删除失败处理asd23
                            }
                        }.bind(that),
                        complete: function () {
                            that.setState({
                                dictTableLoading: false
                            });
                        }
                    })
                } else if (type == "children") {
                    that.setState({
                        childrenTableLoading: true
                    });
                    record.dict_item_id = record.key;
                    util.httpRequest({
                        type: "POST", url: "dict010309.json", params: record, success: function (res) {
                            if (res.ret_code === "0000") {
                                that.queryChildren({dict: record.dict});
                                that.updateLocalDict();
                            } else {
                                //@TODO 字典子项删除失败处理
                            }
                        }.bind(that),
                        complete: function () {
                            that.setState({
                                childrenTableLoading: false
                            });
                        }
                    })
                }
            },
            onCancel() {
            }
        });
    }
    config() {
        return {
            getFieldProps: {},
            tableColumns: [{
                title: '字典标识',
                dataIndex: 'dict',
                key: 'dict',
                width: 300
            }, {
                title: '字典名称',
                dataIndex: 'dictname',
                key: 'dictname',
                width: 200
            }, {
                title: '字典上级组',
                dataIndex: 'groupdict',
                key: 'groupdict',
                width: 100,
                render: function (value) {
                    if (value == "ROOT") {
                        return "";
                    }
                    return value;
                },
            }, {
                title: '用户操作',
                dataIndex: '',
                key: 'X',
                width: 150,
                render: (text, record, index) => (
                    //     {(this.state.edit && this.state.delete) ? <span className="ant-divider"></span> : null }
                    // {this.state.delete ?
                    //     <a className="a-operate" type="primary" size="small" onClick={this.remove.bind(this, "dict", record)}>删除</a> : null}
                    <div>
                        {this.state.edit ?
                            <a className="a-operate" type="primary" size="small"
                               onClick={this.modify.bind(this, "dict", record)}>修改</a> : null}
                    </div>)
            }],
            childrenColumns: [{
                title: '子项值',
                dataIndex: 'itemkey',
                key: 'itemkey',
                width: "30%"
            }, {
                title: '子项名',
                dataIndex: 'itemval',
                key: 'itemval',
                width: "30%"
            }, {
                title: '用户操作',
                dataIndex: 'descript',
                key: 'descript',
                width: "40%",
                render: (text, record, index) => (
                    //     {(this.state.edit && this.state.delete) ? <span className="ant-divider"></span> : null }
                    // {this.state.delete ? <a  className="a-operate" type="primary" size="small"
                    //                          onClick={this.remove.bind(this, "children", record)}>删除</a> : null}
                    <div>
                        {this.state.edit ? <a className="a-operate" type="primary" size="small"
                                              onClick={this.modify.bind(this, "children", record)}>修改</a> : null}

                    </div>)
            }]
        }
    }

    //sf
    render() {
        const config = this.config();
        const columns1 = config.tableColumns;
        const columns2 = config.childrenColumns;
        // q
        return (
            <div>
                <Search search={this.search.bind(this)}></Search>
                <Collapse className="m-t-10" defaultActiveKey={['1']}>
                    <Panel header="数据字典信息列表" key="1">
                        <Row>
                            <Col span={15}>
                                {this.state.add ? <Button className="addBtn" type="primary"
                                                          onClick={this.addDict.bind(this)}>+ 新增</Button> : null}
                                <Table dataSource={this.state.dataSource} columns={columns1} size="small"
                                       loading={this.state.dictTableLoading}
                                       onRowClick={this.onRowClick.bind(this)} indentSize={25}
                                       pagination={false} scroll={{y: 300}}
                                ></Table>
                            </Col>
                            <Col span={9}>
                                {this.state.add ? <span><Button className="addBtn btnMarginVertical" type="primary"
                                                                onClick={this.addChildren.bind(this)}
                                                                disabled={this.state.CBState}
                                    >+  新增</Button><Button className="addBtn btnMarginVertical" type="primary"
                                                           onClick={this.onTongBu.bind(this)}
                                                           disabled={this.state.CBState}
                                    >同步</Button> </span> : null}
                                <Table dataSource={this.state.childrenData} columns={columns2} size="small"
                                       loading={this.state.childrenTableLoading}
                                       pagination={false} scroll={{y: 300}}
                                ></Table>
                            </Col>
                        </Row>
                    </Panel>
                </Collapse>
                <Modal title={this.state.dictModalTitle} visible={this.state.dictVisible} closable={false}
                       onCancel={this.hideModal.bind(this)}
                       footer={[
                           <Button key="back" type="ghost" size="large"
                                   onClick={this.handleCancel.bind(this)}>取消</Button>,
                           <Button key="submit" type="primary" size="large" loading={this.state.bloading}
                                   onClick={this.handleSubmit.bind(this, "dict", this.state.operate)}>
                               {this.state.operate == "add" ? "新增" : "修改"}
                           </Button>
                       ]}
                >
                    <DictForm ref="form" key={this.state.key1} optionData={this.state.optionData}
                              data={this.state.diceFormData} isAdd={this.state.isAdd}></DictForm>
                </Modal>
                <Modal title={this.state.dictModalTitle} visible={this.state.childrenVisible} closable={false}
                       onCancel={this.hideModal.bind(this)}
                       footer={[
                           <Button key="back" type="ghost" size="large"
                                   onClick={this.handleCancel.bind(this)}>取消</Button>,
                           <Button key="submit" type="primary" size="large" loading={this.state.bloading}
                                   onClick={this.handleSubmit.bind(this, "children", this.state.operate)}>
                               {this.state.operate == "add" ? "新增" : "修改"}
                           </Button>
                       ]}
                >
                    <ChildrenForm ref="form" key={this.state.key2} data={this.state.childrenFormData}
                                  isAdd={this.state.isAdd}></ChildrenForm>
                </Modal>

            </div>)
    }
}
export default Dict;
